package com.chookss.home.rank;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.entity.NewsEntiry;
import com.chookss.mine.adapter.MyNewsListsAdapter;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.google.gson.reflect.TypeToken;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

public class RankLinkActivity extends BaseAct {
    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.tvShareNum)
    TextView tvShareNum;
    @BindView(R.id.tvShareNumAll)
    TextView tvShareNumAll;
    @BindView(R.id.tvBrowse)
    TextView tvBrowse;
    @BindView(R.id.tvComplaints)
    TextView tvComplaints;
    @BindView(R.id.ivBrowseArrow)
    ImageView ivBrowseArrow;
    @BindView(R.id.llBrowse)
    LinearLayout llBrowse;
    @BindView(R.id.ivComplaintsArrow)
    ImageView ivComplaintsArrow;
    @BindView(R.id.ivTimeArrow)
    ImageView ivTimeArrow;
    @BindView(R.id.llComplaints)
    LinearLayout llComplaints;
    @BindView(R.id.rvView)
    RecyclerView recyclerView;
    @BindView(R.id.srlView)
    SmartRefreshLayout smrRf;
    @BindView(R.id.ivNone)
    ImageView ivNone;
    @BindView(R.id.tvNone)
    TextView tvNone;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.llBg)
    LinearLayout llBg;
    private int currentPage = 1;
    private boolean isEnd = false;//是否到底
    private RankLinkAdapter adapter;
    private ArrayList<RankLinkEntity> list = new ArrayList<>();
    private int  tsSort = -1, viewSort = -1,timeSort=0;  //0倒序1正序
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.activity_rank_link);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        commonTitleTxt.setText("我的链接");
        ivNone.setBackgroundResource(R.drawable.icon_default_no_common);
        tvNone.setText("暂无数据");
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager
                .VERTICAL, false));
        recyclerView.setPadding(Utils.dip2px(this, 12), 0, Utils.dip2px(this, 12), 0);

        adapter = new RankLinkAdapter(R.layout.item_rank_link, this, list);
        recyclerView.setAdapter(adapter);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                isEnd = false;
                getData();
            }
        });
        smrRf.autoRefresh();
        selectMySuYuanNum();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        smrRf.autoRefresh();
    }

    private void selectMySuYuanNum() {
        MyHttpRequest.getDefault().getRequestCompat(null, Urls.selectMySuYuanNum, SignUtils2.makeSignStr(null), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        tvShareNumAll.setText("/"+Utils.changeNumber(jsonObject1.getString("totalNum")));
                        tvShareNum.setText(Utils.changeNumber(jsonObject1.getString("effNum"))+"");
                        tvBrowse.setText(Utils.changeNumber(jsonObject1.getString("viewNum"))+"");
                        tvComplaints.setText(Utils.changeNumber(jsonObject1.getString("tsNum"))+"");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String errorMsg) {
            }
        });
    }

    private void getData() {
        Map<String, String> allmap = new HashMap<>();
        if (viewSort == 0) {
            allmap.put("viewSort", "desc");
        } else if (viewSort == 1) {
            allmap.put("viewSort", "asc");
        }
        if (tsSort == 0) {
            allmap.put("tsSort", "desc");
        } else if (tsSort == 1) {
            allmap.put("tsSort", "asc");
        }
        if (timeSort == 0) {
            allmap.put("timeSort", "desc");
        } else if (timeSort == 1) {
            allmap.put("timeSort", "asc");
        }
        allmap.put("pageNum", currentPage + "");
        allmap.put("pageSize", "20");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<RankLinkEntity>>>() {
        }.getType(), null, Urls.selectMySuYuanList, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<List<RankLinkEntity>>() {
            @Override
            public void onSuccess(List<RankLinkEntity> data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (smrRf == null || llNone == null) {
                    return;
                }
                int oldIndex = list.size();
                if (data != null && data.size() > 0) {
                    list.addAll(data);
                    adapter.notifyItemRangeChanged(oldIndex, data.size());
                    smrRf.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        smrRf.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                    }

                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
            if(map.containsKey("statusCd")&&map.containsKey("linkUid")){
                saveData(map.get("linkUid"),map.get("statusCd"));
            }
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
        }
    }
    private void saveData(String linkUid,String statusCd) {
        Map<String, String> map = new HashMap<>();
        map.put("statusCd",statusCd);
        map.put("linkUid", linkUid);
        MyHttpRequest.postRequest(Urls.updateStatusCd, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        selectMySuYuanNum();
                        for (int i = 0; i <list.size() ; i++) {
                             if(list.get(i).getLinkUid().equals(linkUid)){
                                 list.get(i).setStatusCd(statusCd);
                             }
                        }
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }
    @OnClick(R.id.common_title_back)
    public void onClick() {
        finish();
    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }


    @OnClick({R.id.common_title_back, R.id.llTime,R.id.llBrowse, R.id.llComplaints})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.llBrowse:
                tsSort=-1;
                ivComplaintsArrow.setBackgroundResource(R.drawable.iv_paixu_default);
                timeSort=-1;
                ivTimeArrow.setBackgroundResource(R.drawable.iv_paixu_default);
                if (viewSort == 0) {
                    viewSort = 1;
                    ivBrowseArrow.setBackgroundResource(R.drawable.iv_paixu_down);
                } else {
                    viewSort = 0;
                    ivBrowseArrow.setBackgroundResource(R.drawable.iv_paixu_up);
                }
                smrRf.autoRefresh();
                break;
            case R.id.llComplaints:
                viewSort=-1;
                ivBrowseArrow.setBackgroundResource(R.drawable.iv_paixu_default);
                timeSort=-1;
                ivTimeArrow.setBackgroundResource(R.drawable.iv_paixu_default);
                if (tsSort == 0) {
                    tsSort = 1;
                    ivComplaintsArrow.setBackgroundResource(R.drawable.iv_paixu_down);
                } else {
                    tsSort = 0;
                    ivComplaintsArrow.setBackgroundResource(R.drawable.iv_paixu_up);
                }
                smrRf.autoRefresh();
                break;
            case R.id.llTime:
                viewSort=-1;
                ivBrowseArrow.setBackgroundResource(R.drawable.iv_paixu_default);
                tsSort=-1;
                ivComplaintsArrow.setBackgroundResource(R.drawable.iv_paixu_default);
                if (timeSort == 0) {
                    timeSort = 1;
                    ivTimeArrow.setBackgroundResource(R.drawable.iv_paixu_down);
                } else {
                    timeSort = 0;
                    ivTimeArrow.setBackgroundResource(R.drawable.iv_paixu_up);
                }
                smrRf.autoRefresh();
                break;
        }
    }
}
